/*
 * @Author: zhangyang
 * @Date: 2021-09-09 09:43:51
 * @LastEditTime: 2021-09-18 14:57:38
 * @Description: 前端路由
 */
import type { RouteRecordRaw } from 'vue-router';
import { createRouter, createWebHistory } from 'vue-router';
import pages from './pages.json';

/**
 * 权限控制
 * 免登陆路由白名单
 */
export const commonRoutes: string[] = [
  '/',
  '/404',
  '/base/login',
  '/base/register',
  '/base/resetPasswd',
];

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    component: () => import('/src/views/home/master.vue'),
  },
];

/**
 * 根据配置文件成成路由
 */
for (const path of Object.keys(pages)) {
  const _conf = (pages as unknown as any)[path as unknown as string] as {
    name: string;
    title: string;
  }[];
  for (const { name, title } of _conf) {
    const routeItem: RouteRecordRaw = {
      path: `/${path}/${name}`,
      name,
      // 查询参数注入为组件参数
      props: (route) => route.query,
      // 动态生成的导入名称必须为相对路径，而且必须有扩展名
      // https://github.com/rollup/plugins/tree/master/packages/dynamic-import-vars#limitations
      component: () => import(`../views/${path}/${name}.vue`),
      meta: { title },
    };
    routes.push(routeItem);
  }
}

// 页面不存在，404,必须放在最后！！！
routes.push({
  path: '/:pathMatch(.*)*',
  name: 'NotFound',
  props: (route) => route.query,
  component: () => import('/src/views/404.vue'),
});

const router = createRouter({
  history: createWebHistory(),
  routes,
  scrollBehavior() {
    return { top: 0 };
  },
});

export default router;
export { routes };
